﻿using JESAI.ClamAV.NetScannerCore.Command;
using JESAI.ClamAV.NetScannerCore.Configuration;
using JESAI.ClamAV.NetScannerCore.Exceptions;
using JESAI.ClamAV.NetScannerCore.Extensions;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace JESAI.ClamAV.NetScannerCore.TcpClients.Builder
{
    /// <summary>
    /// tcp连接构建程序
    /// </summary>
    public class TransientScannerTcpClientBuilder : IScannerTcpClientBuilder, IDisposable
    {
        /// <summary>
        /// 服务器地址
        /// </summary>
        public string Host { get; private set; }

        /// <summary>
        /// 端口
        /// </summary>
        public int Port { get; private set; }
        /// <summary>
        /// tcp连接
        /// </summary>
        public IScannerTCPClient SocketClient { get; private set; }

        /// <summary>
        /// 
        /// </summary>
        public TransientScannerTcpClientBuilder(IClamAvScannerConfiguration clamAvScannerConfiguration)
        {
            Host = clamAvScannerConfiguration.Host;
            Port = clamAvScannerConfiguration.Port;
            SocketClient = new ScannerTCPClient();
        }

        public IScannerTCPClient Build()
        {
            Connect();
            return SocketClient;
        }
        public async Task<IScannerTCPClient> BuildAsync()
        {
            await ConnectAsync();
            return SocketClient;
        }
        private async Task ConnectAsync()
        {
            try
            {
                Close();
                await SocketClient.ConnectAsync(Host, Port);
            }
            catch (Exception ex)
            {
                throw new TCPServerException(Host, Port, ex);
            }

        }
        private void Connect()
        {
            try
            {
                Close();
                SocketClient.Connect(Host, Port);
            }
            catch (Exception ex)
            {
                throw new TCPServerException(Host, Port, ex);
            }
        }

        public void Dispose()
        {
            Close();
        }

        public void Close()
        {
            if (SocketClient != null && SocketClient.Connected)
            {
                SocketClient.Close();
            }
        }
    }
}
